<template>
  <div class="parent">
    <h2>商品详情</h2>
    <!-- 父组件向子组件传递商品数据 -->
    <ChildComponent 
      :product-name="product.name" 
      :product-price="product.price"
      @add-to-cart="handleAddToCart"
    />

    <div class="cart">
      <h3>购物车 ({{ cartList.length }})</h3>
      <button @click="clearCart" class="clear-btn">清空购物车</button>
      <ul v-if="cartList.length > 0">
        <!-- 点击商品项删除 -->
        <li v-for="(item, index) in cartList" :key="index" @click="removeItem(index)">
          {{ item.name }} - ¥{{ item.price }}
        </li>
      </ul>
      <p v-else>购物车为空</p>
    </div>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      // 父组件的商品数据
      product: {
        name: 'Vue实战教程',
        price: 99
      },
      // 购物车列表
      cartList: []
    };
  },
  methods: {
    // 接收子组件传递的商品并添加到购物车
    handleAddToCart(product) {
      this.cartList.push(product);
    },
    // 移除购物车中的商品
    removeItem(index) {
      this.cartList.splice(index, 1);
    },
    // 清空购物车
    clearCart() {
      this.cartList = [];
    }
  }
};
</script>

<style scoped>
.parent {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
}
.cart {
  margin-top: 30px;
  padding: 15px;
  border-top: 1px solid #eee;
}
ul {
  list-style: none;
  padding: 0;
}
li {
  padding: 8px 0;
  border-bottom: 1px dashed #eee;
  cursor: pointer;
}
li:hover {
  color: #e74c3c;
}
.clear-btn {
  margin-bottom: 15px;
  padding: 6px 12px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.clear-btn:hover {
  background: #c0392b;
}
</style>
    